package com.waterstudio.filedownloader.ext.m3u8.bean;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by chensuilun on 2019/3/25.
 */
public final class EncKey {
    @Nullable
    private byte[] iv;
    @Nullable
    private byte[] key;

    public EncKey(@Nullable byte[] key, @Nullable byte[] iv) {
        this.key = key;
        this.iv = iv;
    }

    @Nullable
    public final byte[] getKey() {
        return this.key;
    }

    public final void setKey(@Nullable byte[] bArr) {
        this.key = bArr;
    }

    @Nullable
    public final byte[] getIv() {
        return this.iv;
    }

    public final void setIv(@Nullable byte[] bArr) {
        this.iv = bArr;
    }

    @NonNull
    public final byte[] decrypt(@NonNull byte[] bArr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(this.key, "AES");
        Cipher instance = Cipher.getInstance("AES/CBC/PKCS5Padding");
        instance.init(2, secretKeySpec, new IvParameterSpec(this.iv));
        return instance.doFinal(bArr);
    }
}
